package com.versita.api;

import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;
import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Criterion;

import com.versita.utils.HibernateUtil;

public class DomainAPI {
    Logger logger = Logger.getLogger(DomainAPI.class);

    public void create(Object object)  {
        List<Object> list = new LinkedList<Object>();
        list.add(object);
        this.create(list);
    }

    /**
     * 
     * @param list
     */
    public void create(List<?> list) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.getTransaction().begin();
        for (Object c : list) {
            session.save(c);
        }
        session.getTransaction().commit();
    }

    /**
     * 
     * @param className
     * @param criterions
     * @return
     */
    public List<?> read(String className, List<Criterion> criterions) {
        return this.read(className, criterions, 0, 1024);
    }

    public List<?> read(String className, List<Criterion> criterions, int firstResult, int size) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.getTransaction().begin();
        Criteria criteria = session.createCriteria(className);

        for (Criterion criterion : criterions) {
            criteria.add(criterion);
        }

        criteria.setFirstResult(firstResult);
        criteria.setMaxResults(size);
        List<?> criterion =  criteria.list();
        session.getTransaction().commit();
        return criterion;
    }

    public void update(List<Object> list) {

    }

    /**
     * Delete a list of
     * @param list
     */
    public void delete(List<Object> list) {
        Session session = HibernateUtil.getSessionFactory().getCurrentSession();
        session.beginTransaction();
        for (Object c : list) {
            session.delete(c);
        }
        session.getTransaction().commit();
    }
}
